#!/usr/bin/env python
# -*- coding: cp1252 -*-
from mechanize import Browser
from BeautifulSoup import BeautifulSoup

import re
import Modules.Inventory
import Modules.Budget
import Modules.Util

mech = Browser()
mech.set_handle_robots(False)
mech.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

mech.open("http://www.bricklink.com/search.asp?viewFrom=sa&shipCountryID=BR&invNew=N&q=3004&searchSort=P&sz=25")

itemsPerPage = 500

inventoryPath = "..\\Inventory\\"
inventoryFileName = "Katana with Saya"

inventory = Modules.Inventory.Inventory(inventoryPath + inventoryFileName + ".csv")

budget = Modules.Budget.Budget()

storesByBrick = dict()

print "Processing bricks...",

for item in inventory.Items[:]:
    print "%s" % item.Code,

    url = "http://www.bricklink.com/search.asp?viewFrom=sa&qMin=" + str(item.Quantity) + "&shipCountryID=BR&invNew=N&colorID=" + str(item.ColorNumber) + "&q=" + item.Code + "&searchSort=P&sz=" + str(itemsPerPage)
    page = mech.open(url)
    html = page.read()
    soup = BeautifulSoup(html)

    keytext = soup.find(text=re.compile("Available&nbsp;In"))
    if keytext is None:
        continue

    storesByBrick.clear()

    tr = keytext.parent.findPrevious("tr").findNextSibling()
    while (tr is not None):
        if len(tr.findAll("td")) < 3:
            tr = tr.findNextSibling()
            continue

        td = tr.findAll("td")[3]
        links = td.findAll("a")

        store = links[1].string
        rating = links[2].string
        qty = td.find(text=re.compile("Qty:")).findNextSibling().string
        price = td.find(text=re.compile("Each:")).findNextSibling().string.replace("BRL", "")
        price = float(price) if Modules.Util.is_number(price) else price;

        if store in storesByBrick:
            tr = tr.findNextSibling()
            continue

        storesByBrick[store] = 1

        budget.add(store, rating, item.Code, item.Description, item.Color, item.ColorNumber, item.Quantity, qty, price)

        tr = tr.findNextSibling()

print "ok"

budget.saveBudgetReport(inventoryPath + inventoryFileName + ".budget.txt")
